package com.xmg.p2p.base.controller;

import com.xmg.p2p.base.domain.UserFile;
import com.xmg.p2p.base.service.SystemDictionaryService;
import com.xmg.p2p.base.service.UserFileService;
import com.xmg.p2p.base.util.JSONResult;
import com.xmg.p2p.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class UserFileController {

    @Autowired
    private UserFileService userFileService ;
    @Autowired
    private SystemDictionaryService systemDictionaryService;
    @Autowired
    private ServletContext servletContext;


    /**
     * 加载材料认证页面时
     * @param model
     * @param requset
     * @return
     */
    @RequestMapping("userFile")
    public String userFile(Model model , HttpServletRequest requset){
        //先查询当前用户是否有还有未上传的风控材料  跳转到不同的页面列表
        //查询到所有没有进行分类操作的材料对象集合
        List<UserFile> userFiles = this.userFileService.listUserFilesHasSelectType(false);
        if (userFiles.size() > 0) {
            model.addAttribute("userFiles", userFiles) ;
            model.addAttribute("fileTypes", this.systemDictionaryService.selectByParentSn("fileTypes")) ;
            return "userFiles_commit" ;
        }else{
            //sessionId 这里的这个方法是 在火狐中 上传的图片默认是false是另外一个浏览器 此时传进去的值无法带上id 该方法解决
            model.addAttribute("sessionId", requset.getSession().getId());
            model.addAttribute("userFiles",this.userFileService.listUserFilesHasSelectType(true));
        }
        return "userFiles";
    }


    /**
     * 处理上传用户风控文件
     * @param file
     * @return
     */
    @RequestMapping("userFile_apply")
    @ResponseBody
    public String apply(MultipartFile file){
        String path = this.servletContext.getRealPath("/upload");
        String fileName =  UploadUtil.upload(file, path);
        fileName = "/upload/"+fileName ;
        /*向user file这个表中插入上传的图片的相关信息*/
        this.userFileService.apply(fileName);
        return fileName ;
    }


    /**
     * 处理用户风控文件类型选择
     * @return
     */

    @RequestMapping("userFile_selectType")
    @ResponseBody
    public JSONResult selectType(Long[] id, Long[] fileType){
        JSONResult json =new JSONResult();
        try {
            this.userFileService.selectTypes(id,fileType) ;
        } catch (Exception e) {
            e.printStackTrace() ;
            json.setSuccess(false);
            json.setMsg(e.getMessage());
        }
        return json;
    }
}
